﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Angel.Entities;
using Angel.Daos.IManager;
using Angel.Daos.Manager;
using Angel.Web.Models;
using System.Web.Security; 
namespace Angel.Web.Controllers
{
    public class GroupController : Controller
    {
        private IUserManager userManager;
        private IGroupManager groupManager;
        private IGroup_UserManager groupUserManager;

        public GroupController()
            : this(new UserManager(), new GroupManager(), new Group_UserManager())
        {
        }
        public GroupController(IUserManager _userManager, IGroupManager _groupManager,IGroup_UserManager _groupUserManager)
        {
            userManager = _userManager;
            groupManager=_groupManager;
            groupUserManager = _groupUserManager;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult Index(CreateGroupModel createGroupModel)
        {
            if (ModelState.IsValid)
            {
                try
                {                                          
                        Group group = new Group();
                        group.GroupName = createGroupModel.NameGroup.Trim();
                        groupManager.Add(group);
                        return RedirectToAction("Index");                    
                }
                catch (Exception)
                {
                    ViewBag.MessageError = "Insert fail";
                    return RedirectToAction("Index");
                }
            }
            else
            return View("Index");
        }

        public ActionResult Create()
        {
            return View();
        }

       [HttpPost, ValidateInput(false)]
        public ActionResult Create(CreateGroupModel createGroupModel)
        {           
            try
            {
                if (groupManager.CheckGroupName(createGroupModel.NameGroup)) {
                    ViewBag.ErrGroupname = "Group name is exist";
                    return View("Create");                   
                }
                else{
                Group group = new Group();
                group.GroupName = createGroupModel.NameGroup.Trim();
                groupManager.Add(group);
                return RedirectToAction("Index");
                }
            }
            catch(Exception ex)
            {
                ViewBag.MessageError = ex.Message;
            }
            return View();
        }


  

        [HttpGet,ValidateInput(false)]
        public ActionResult Delete(int? id)
        {
            try
            {
                if (id == null)
                {
                    return RedirectToAction("NotFound", "General", "Error id");
                }     
                var group = groupManager.GetByID(id.Value);
                DeleteGroupModel deleteGroupMode = new DeleteGroupModel();
                deleteGroupMode.id = group.GroupID;
                //--------------------------------------
                deleteGroupMode.name = group.GroupName;
                //---------------------------------------
                return View(deleteGroupMode);
            }
            catch
            {
                return RedirectToAction("NotFound", "General", @"Error definition");
            }
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult Delete(DeleteGroupModel deleteGroupModel)
        {
            try
            {
                Group group = groupManager.GetByID(deleteGroupModel.id);
                groupManager.Delete(group);
            }
            catch (Exception ex)
            {
                ViewBag.MessageError = ex.Message;
            }

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult Search(SearchGroupModels searchGroupModel)
        {
            //Output to Output Windows.
            System.Diagnostics.Debug.Write("HTTP POST");

            IEnumerable<Group> result = groupManager.Search(searchGroupModel.NameGroup,0,2);
            ViewBag.result = result;
            return View();
        }

        public ActionResult Search()
        {
            return View();
        }

        public String SearchXML(String name, int start, int max)
        {
            System.Diagnostics.Debug.WriteLine("Search XML");
            String txtResult = "";
            //start = 5;
            int pages = 0;
            int rows = 0;
            int currentPage = 0;
            //Get result filter
            IEnumerable<Group> listGroup = groupManager.Search(name.Trim(), start, max).OrderBy(m => m.GroupName);
            if (listGroup.Count() != 0)
            {
                //return limit rows
                IEnumerable<Group> result = listGroup.Skip(start).Take(max);
                rows = listGroup.Count();
                //Set total of pages
                if (rows % max == 0)
                {
                    pages = rows / max;
                }
                else
                {
                    pages = rows / max + 1;
                }
                //Set current page number
                currentPage = start / max + 1;
                start++;

                System.Diagnostics.Debug.Write("Max:" + max + "  Rows:" + rows + "  PageTotal:" + pages + "  PageNumber:" + currentPage + "\n");
                //Set result string
                txtResult += "<Groups>";

                foreach (Group item in result)
                {
                    txtResult += "<Group>";
                    txtResult += "<Rows>" + rows + "</Rows>";
                    txtResult += "<CurrentPage>" + currentPage + "</CurrentPage>";
                    txtResult += "<Pages>" + pages + "</Pages>";
                    txtResult += "<StartRow>" + start + "</StartRow>";
                    txtResult += "<Id>" + item.GroupID.ToString() + "</Id>";
                    txtResult += "<Name>" + editHTMLTag(item.GroupName.ToString()) + "</Name>";
                    txtResult += "<NumberOfUser>" + groupManager.countUser(item) + "</NumberOfUser>";
                    txtResult += "</Group>";
                    //System.Diagnostics.Debug.WriteLine("new line:" + groupManager.countUser(item));
                }
                txtResult += "</Groups>";
            }
           
            return txtResult;
        }

        [HttpPost]
        public ActionResult Filter(JsonInfo jsonInfo)
        {

            System.Diagnostics.Debug.WriteLine("Json Action");
            int pages = 0;
            int rows = 0;
            int currentPage = 0;
            if (jsonInfo.Name == null)
                jsonInfo.Name = "";
            List<FilterGroupModel> Groups = new List<FilterGroupModel>();
            //Get result filter
            IEnumerable<Group> listGroup = groupManager.Search(jsonInfo.Name.Trim(), jsonInfo.Start, jsonInfo.Max).OrderBy(m => m.GroupName);
            if (listGroup.Count() != 0)
            {
                //return limit rows
                IEnumerable<Group> result = listGroup.Skip(jsonInfo.Start).Take(jsonInfo.Max);
                rows = listGroup.Count();
                //Set total of pages
                if (rows % jsonInfo.Max == 0)
                {
                    pages = rows / jsonInfo.Max;
                }
                else
                {
                    pages = rows / jsonInfo.Max + 1;
                }
                //Set current page number
                currentPage = jsonInfo.Start / jsonInfo.Max + 1;
                jsonInfo.Start++;

                System.Diagnostics.Debug.Write("Max:" + jsonInfo.Max + "  Rows:" + rows + "  PageTotal:" + pages + "  PageNumber:" + currentPage + "\n");
                
                foreach (Group item in result)
                {
                    Groups.Add(new FilterGroupModel(item.GroupID, editHTMLTag(item.GroupName), groupManager.countUser(item)));
                }
            }
            return Json(new FilterResultModel(rows, pages, currentPage, jsonInfo.Start, Groups));
        }
        //******************
        public ActionResult Edit(int? id)
        {
            try
            {
                if(id.Value== null)
                {
                    return RedirectToAction("NotFound", "General", "Errror id can not be null");
                }
                IEnumerable<Group_User> list = groupManager.GetData(id.Value);
                var Name = groupManager.GetByID(id.Value);
                ViewBag.GroupName = Name.GroupName;
                ViewBag.list = list;
                ViewBag.Id = id;
                return View();
            }
            catch{
                return RedirectToAction("NotFound", "General", @"Error definition");
            }
        }

        public ActionResult DeleteMember(int id)
        {            
            var delMem = groupUserManager.GetByID(id);
            return View(delMem);
        }

        [HttpPost]
        public ActionResult DeleteMember(Group_User groupUser)
        {
            groupUserManager.Delete(groupUser);
            return RedirectToAction("Edit", "Group", new { id=groupUser.GroupID});
        }

        public bool IsUserInGroup(User user, Group_User groupUser)
        {
            IEnumerable<Group_User> list = groupManager.GetData(groupUser.GroupID);   
            foreach (var item in list)
            {
                if (user.UserID == item.UserID) return true;
            }
            return false;
        }

        public ActionResult AddMember(int id)
        {
            ViewBag.Id = id;
            return View();
        }
        [HttpPost]
        public ActionResult AddMember(MemberGroup  addMember)
        {
            Group_User groupUser = new Group_User();
            groupUser.GroupID = addMember.GroupId;
            string name = addMember.UserName;
            User user = new User();            
            user=userManager.getByUserName(name);
            if (user != default(User) && !IsUserInGroup(user, groupUser))
            {                                              
                    groupUser.UserID = user.UserID;
                    groupUserManager.CreateUserOfGroup(groupUser);
                    
                return RedirectToAction("Edit", "Group", new { id = groupUser.GroupID });
            }
            if (user == default(User))
            {
                ViewBag.NotExist = "A UserName is not exist in database!";

                return View();
               // return RedirectToAction("Error", "General", new {id =1});
            }

            if (IsUserInGroup(user, groupUser))
            {
                
                ViewBag.Exist = "The UserName is exist in this Group!";
                user = default(User);
                return View("AddMember");
                //return RedirectToAction("Error", "General", new { id = 2 });
            }
            return RedirectToAction("Edit", "Group", new { id = groupUser.GroupID });
      
        }
        private static String editHTMLTag(String source)
        {
            Char[] arrString = source.ToCharArray();
            String target = "";
            foreach (Char item in arrString)
            {
                if (item == '<')
                {
                    target += "&#65308;";
                }
                else if (item == '>')
                {
                    target += "&#65310;";
                }
                else if (item == '"')
                {
                    target += "&quot;";
                }
                else if (item == '*')
                {
                    target += "&#42;";
                }
                else if (item == '&')
                {
                    target += "&amp;";
                }
                else
                {
                    target += item.ToString();
                }
            }
            System.Diagnostics.Debug.WriteLine(target);
            return target;
        }
    }
}
